package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author dlc
 * @Date 2023/11/11
 * @Description TODO
 * @Version 0.0.1
 */
@Component
public class RedisIdWorker {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 指定一个开始时间
    private static final long BEGIN_TIMESTAMP = 1640995200;

    public long nextId(String prefix) {
        // 当前时间戳
        LocalDateTime currentTime = LocalDateTime.now();
        long second = currentTime.toEpochSecond(ZoneOffset.UTC);
        // 计算过了多少秒
        long timestamp = second - BEGIN_TIMESTAMP;

        // 获取当前日期
        String format = currentTime.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 获取序列号【这里肯定有一个值，】
        long count = stringRedisTemplate.opsForValue().increment("inr:" + prefix + ":" + format);

        // 拼接返回
        // 往左移动32位，然后和序号做 | 的操作，也就是拼接
        return timestamp << 32 | count;
    }

    public static void main(String[] args) {
        // 生成一个 2022年1月1日的秒数作为基数
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second: " + second);
    }
}
